//
//  AFGetData.m
//  MVideo
//
//  Created by Lin Eidan on 14-4-15.
//  Copyright (c) 2014年 taomee. All rights reserved.
//

#import "AFGetData.h"
#import "UIImageView+WebCache.h"
#import "LocalFileManage.h"
#import "config.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation AFGetData

-(id)init{
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}

-(void)setUp{
    
    //public
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    self.networkStateManager = [AFNetworkReachabilityManager sharedManager];
    [self.networkStateManager startMonitoring];
    
    //iOS6 不写这句话，默认就是按照json的去解析，但有的是m3u8，所以干脆不解析。responseObject就是NSData，然后后面，自己去解析.
    self.operationManager = [[AFHTTPRequestOperationManager alloc] init];
    self.operationManager.responseSerializer =[AFHTTPResponseSerializer serializer];
    
    NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration defaultSessionConfiguration];
    self.sessionHttpManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    self.sessionHttpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
}


+ (AFGetData *)sharedInstance
{
    
    static AFGetData *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[AFGetData alloc] init];
    });
    return _sharedInstance;
}



#pragma mark - 取消一般网络请求，不包括下载

-(void)removeAllGetAndPostRequest{
    if (isiOS7) {
        for (NSURLSessionTask *task in self.sessionHttpManager.tasks) {
            [task cancel];
        }
    } else {
        [self.operationManager.operationQueue cancelAllOperations];  //iOS6
    }
}

#pragma mark - 通用的一般网络请求

-(id)startGet:(NSString *)url andResultIsJSON:(BOOL)iSJSON andRequestCompletion:(completionBlock)block{
    if (isiOS7) {
        return [self startGet:url andResultIsJSON:iSJSON andTaskCompletion:^(NSURLSessionDataTask *task, id responseJSON, BOOL isSuccess){
            block(responseJSON,isSuccess);
        }];
    }else{
        return [self startGet:url andResultIsJSON:iSJSON andCompletion:^(AFHTTPRequestOperation *operation, id responseJSON, BOOL isSuccess){
            block(responseJSON,isSuccess);
        }];
    }
}

-(id)startPost:(NSString *)url andInfo:(NSDictionary *)infoDic andDataBodyBlock:(dataBodyBlock)dataBlock andRequestCompletion:(completionBlock)block{
    if (isiOS7) {
        return [self startPost:url andInfo:infoDic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
            dataBlock(formData);
        } andTaskCompletion:^(NSURLSessionDataTask *task, id responseJSON, BOOL isSuccess) {
            block(responseJSON,isSuccess);
        }];
    }else{
        return [self startPost:url andInfo:infoDic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
            dataBlock(formData);
        } andCompletion:^(AFHTTPRequestOperation *operation, id responseJSON, BOOL isSuccess) {
            block(responseJSON,isSuccess);
        }];
    }
}


#pragma mark - iOS6 一般请求数据

-(AFHTTPRequestOperation *)startGet:(NSString *)url andResultIsJSON:(BOOL)iSJSON andCompletion:(completionOperationBlock)block{
    
    AFHTTPRequestOperation *operation = [self.operationManager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
        if (responseObject != nil) {
            block(operation,(iSJSON ? [self convertDataToJsonFromData:responseObject] : responseObject),YES);
        }else{
            block(operation,nil,NO);
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        block(operation,nil,NO);
    }];
    
    return operation;
}

-(AFHTTPRequestOperation *)startPost:(NSString *)url andInfo:(NSDictionary *)infoDic andDataBodyBlock:(dataBodyBlock)dataBlock andCompletion:(completionOperationBlock)block{
    
    AFHTTPRequestOperation *operation = [self.operationManager POST:url parameters:infoDic constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
        dataBlock(formData);
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject != nil) {
            block(operation,[self convertDataToJsonFromData:[operation responseData]],YES);
        }else{
            block(operation,nil,NO);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        block(operation,nil,NO);
    }];
    
    return operation;
}




#pragma mark - iOS7 一般请求数据

-(NSURLSessionDataTask *)startGet:(NSString *)url andResultIsJSON:(BOOL)iSJSON andTaskCompletion:(completionTaskBlock)block{
    NSURLSessionDataTask *dataTask = [self.sessionHttpManager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject != nil) {
            block(task,(iSJSON ? [self convertDataToJsonFromData:responseObject] : responseObject),YES);
        }else{
            block(task,nil,NO);
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        block(task,nil,NO);
    }];
    
    return dataTask;
}


-(NSURLSessionDataTask *)startPost:(NSString *)url andInfo:(NSDictionary *)infoDic andDataBodyBlock:(dataBodyBlock)dataBlock andTaskCompletion:(completionTaskBlock)block{
    
    NSURLSessionDataTask *dataTask = [self.sessionHttpManager POST:url parameters:infoDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        dataBlock(formData);
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (responseObject != nil) {
            block(task,[self convertDataToJsonFromData:responseObject],YES);
        }else{
            block(task,nil,NO);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        block(task,nil,NO);
    }];
    
    return dataTask;
}


#pragma mark - Public And Image

//将数据转成字典或者数组
-(id)convertDataToJsonFromData:(NSData *)data{
    NSError * errorJSON;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&errorJSON];
    return jsonObject;
}

//SDwebImage方法请求图片
-(void)initSDWebImage:(NSString *)url andTrueImageView:(UIImageView *)trueImageView andPlaceholderImage:(UIImage *)placeholder{
    __block UIImageView *blockSelf=trueImageView;
    if (nil == url) {
        trueImageView.image=nil;
        return;
    }
    
    [trueImageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (!cacheType) {  //0没有缓存 1硬盘  2内存  没有缓存的时候才有动画.
            blockSelf.alpha=0;
            [UIView animateWithDuration:0.3 animations:^{
                blockSelf.alpha=1;
            }];
        }
    }];
}

//开机画面图的加载，用url做为key，图片只有全部load完毕，这个图片才会以这个key存在本地，本地是否有这个key用来标记是否显示开机画面图
-(BOOL)initSDWebImageThatLaunchAction:(NSString *)url andTrueImageView:(UIImageView *)trueImageView{
    
    __block UIImageView *blockSelf=trueImageView;
    [trueImageView setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        if (!cacheType) {  //从网络取来的，证明是第一次，才会存在本地。
            [[SDImageCache sharedImageCache] storeImage:blockSelf.image forKey:url toDisk:YES];
        }
    }];
    
    UIImage *localImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:url]; //从本地，根据这个地址去取，看有没有,换地址了，就是没有，但上面会去请求新的地址，然后存起来，下次用
    if (localImage) {
        return YES;
    }else{
        return NO;
    }
    
}

#pragma mark -网络管理

-(BOOL)theNetworkTypeIsNone{
    return !self.networkStateManager.reachable;  //没网络就为YES
}

-(BOOL)theNetworkTypeIs3G{
    return self.networkStateManager.reachableViaWWAN;
}

-(BOOL)theNetworkTypeIsWifi{
    return self.networkStateManager.reachableViaWiFi;
}

-(NSString *)getNetworkTypeString{
    NSString *str;
    if (self.networkStateManager.reachableViaWiFi) {
        str = @"Wifi";
    }else if (self.networkStateManager.reachableViaWWAN){
        str = @"3G";
    }else{
        str = @"None";
    }
    return str;
}


@end
